<!--
  文件描述：
  创建时间：2025/2/20 18:41
  创建人：FanHao
-->
<template>
  <div>
    <el-container v-if="status==='add'||status==='edit'">
      <el-form :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="附件">
              <el-upload
                  v-model:file-list="fileList"
                  ref="upload"
                  :multiple="true"
                  :limit="5"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  支持扩展名：.doc/.docx/.pdf/.xls/.xlsx，单个文件不超过20MB
                </div>
              </el-upload>
              <!-- 文件下载 -->

              <div v-if="existingAttachments.length" class="attachment-list">
                <div v-for="file in existingAttachments" :key="file.id" class="attachment-item">
                  <el-button type="primary" link @click="downloadFile(file)">
                    {{ file.name }}
                  </el-button>
                  <el-button type="danger" size="small" text @click="removeExistingFile(file.id)">
                    删除
                  </el-button>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="内容">
              <div class="editor-container">
                <Toolbar
                    class="toolbar"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    class="editor"
                    v-model="form.content"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end">
          <el-col :span="4">
            <el-button @click="this.$emit('update:visible', false)">取消</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-container>

    <el-container v-else>
      <div class="preview" style="width: 100%">
        <div style="float: none; margin: 0 auto; width: 80%">
          <h1 style="text-align: center; width: 100%;font-size: 24px">{{ form.title }}</h1>
        </div>
        <br>
        <div class="content" v-html="form.content"></div>

        <div v-if="existingAttachments.length" class="attachment-list">
          <div v-for="file in existingAttachments" :key="file.id" class="attachment-item">
            <el-button type="primary" link @click="downloadFile(file)">
              {{ file.name }}
            </el-button>
          </div>
        </div>


      </div>
    </el-container>
  </div>
</template>

<script>
import {ElMessage} from 'element-plus'
import {Editor, Toolbar} from '@wangeditor-next/editor-for-vue'
import {
  AddAnnouncements, DownloadFile,
  GetAnnouncementById,
  UpdateAnnouncements,
} from "@/api/index.js";

export default {
  components: {
    Editor, Toolbar,
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    status: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        id: this.id,
        title: '',
        content: "",
        attachments: []

      },
      editor: null,

      toolbarConfig: {
        excludeKeys: ['group-video',]
      },

      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            base64LimitSize: 1024 * 1024, // 限制上传图片为1MB
            // 其他上传图片相关配置
          },
          // 你可以在这里添加更多的菜单配置
        },
      },
      mode: 'default',
      fileList: [],
      files: [],
      existingAttachments: [],
      removedAttachmentIds: [],
    };
  },
  computed: {},
  created() {
  },
  mounted() {
    this.fetch()
  },

  methods: {
    // 收集文件但不立即上传
    handleFileChange(file) {
      this.files.push(file.raw)
    },
    handleFileRemove(file) {
      this.files = this.files.filter(f => f.uid !== file.uid)
    },
    handleCreated(editor) {
      this.editorRef = editor // 记录 editor 实例，重要！
    },
    removeExistingFile(fileId) {
      this.removedAttachmentIds.push(fileId)
      this.existingAttachments = this.existingAttachments.filter(f => f.id !== fileId)
    },
    async downloadFile(file) {
      const response = await DownloadFile(file.id)
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.download = file.name; // 直接使用文件名（已编码）
      link.click();
    },

    async handleSubmit() {
      const formData = new FormData()
      const dtoJson = JSON.stringify({
        id: this.form.id,
        title: this.form.title,
        content: this.form.content,
        removedAttachmentIds: this.removedAttachmentIds
      });
      const dtoBlob = new Blob([dtoJson], {type: 'application/json'});
      formData.append('dto', dtoBlob)
      this.files.forEach(file => {
        formData.append('files', file)
      })
      let res;
      if (this.status === 'add') {
        res = await this.addAnnouncement(formData)
      }
      if (this.status === 'edit') {
        res = await this.editAnnouncement(formData)
      }
      if (res.code === 200) {
        ElMessage.success('操作成功')
        this.$emit('update:visible', false)
        this.$emit('refresh')
      } else {
        ElMessage.error('操作失败')
      }
    },

    async addAnnouncement(formData) {
      const res = await AddAnnouncements(formData)
      return res
    },
    async editAnnouncement(formData) {
      const res = await UpdateAnnouncements(formData)
      return res
    },

    async fetch() {
      if (this.status !== 'add') {
        const res = await GetAnnouncementById(this.id)
        if (res.code === 200) {
          this.form = res.data
          this.existingAttachments = res.data.attachments || []
        }
      } else {
        setTimeout(() => {
          this.form.content = '<p></p>'
        }, 50)
      }
    }
  },
  beforeUnmount() {
    if (this.editorRef) {
      this.editorRef.destroy()
    }
  },

}
</script>
<style src="@wangeditor-next/editor/dist/css/style.css"></style>
